﻿using System.Collections.Generic;
using SharpDX.RawInput;

namespace FadeGameFramework.UI
{
    public class ControlManager : IUpdatable
    {
        private readonly SortedList<int, Control> controlList = new SortedList<int, Control>();
        private readonly IRenderTarget renderTarget;

        public ControlManager(IRenderTarget renderTarget) {
            this.renderTarget = renderTarget;
            Game.Instance.InputManager.OnMouseDown += InputManager_OnMouseDown;
            Game.Instance.InputManager.OnMouseUp += InputManager_OnMouseUp;
        }

        public void Update(float dt) {
            foreach (var control in controlList) {
                control.Value.Update(dt);
            }
        }

        public void AddControl(Control control) {
            controlList.Add(control.Zorder, control);
        }

        public void Draw() {
            foreach (var control in controlList.Values) {
                renderTarget.DrawBitmap(control.Texture, control.Position);
            }
        }

        private void InputManager_OnMouseDown(MouseInputEventArgs e) {
            foreach (var control in controlList.Values) {
                var mousePosition = Game.Instance.InputManager.MousePosition;
                if (control.Contains(mousePosition)) {
                    control.RaiseEvent(ControlEventState.MouseDown,
                        new MouseEventArgs(mousePosition, e.Buttons, e.ButtonFlags));
                    return;
                }
            }
        }

        private void InputManager_OnMouseUp(MouseInputEventArgs e) {
            foreach (var control in controlList.Values) {
                var mousePosition = Game.Instance.InputManager.MousePosition;
                if (control.Contains(mousePosition)) {
                    control.RaiseEvent(ControlEventState.MouseUp,
                        new MouseEventArgs(mousePosition, e.Buttons, e.ButtonFlags));
                    return;
                }
            }
        }
    }
}